package com.heima.media.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.PageResponseResult;
import com.heima.common.dto.ResponseResult;
import com.heima.common.dto.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.UserThreadLocalUtil;
import com.heima.media.dto.WmSensitiveDto;
import com.heima.media.entity.WmSensitive;
import com.heima.media.mapper.WmSensitiveMapper;
import com.heima.media.service.IWmSensitiveService;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * <p>
 * 敏感词信息表 服务实现类
 * </p>
 *
 * @author djc
 * @since 2022-10-03
 */
@Service
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements IWmSensitiveService {

    @Override
    public ResponseResult listByPage(WmSensitiveDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        Page<WmSensitive> page = new Page<>(dto.getPage(), dto.getSize());

        LambdaQueryWrapper<WmSensitive> queryWrapper = new LambdaQueryWrapper();

        if (StringUtils.isNotBlank(dto.getName())) {
            queryWrapper.like(WmSensitive::getSensitives,dto.getName());
        }
        queryWrapper.orderByDesc(WmSensitive::getCreatedTime);

        Page<WmSensitive> page1 = this.page(page, queryWrapper);

        return new PageResponseResult(dto.getPage(), dto.getSize(), page1.getTotal(), page1.getRecords());
    }

    @Override
    public ResponseResult saveSensitive(WmSensitiveDto dto) {
        User user = UserThreadLocalUtil.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        WmSensitive one = this.getOne(Wrappers.lambdaQuery(WmSensitive.class).eq(WmSensitive::getSensitives, dto.getSensitives()));
        if (one == null) {
            WmSensitive wmSensitive = new WmSensitive();
            wmSensitive.setSensitives(dto.getSensitives());
            wmSensitive.setCreatedTime(new Date());
            this.save(wmSensitive);
            ResponseResult.okResult();
        }
        return ResponseResult.errorResult(AppHttpCodeEnum.DATA_EXIST);
    }
}
